<template>
    <a-modal v-model:visible="modalVisible" title="绑定微信" @ok="handleOk" width="400px">
        <a-form class="query-list-form" :model="form">
            <div class="qr-code-form">
                <div class="mb-32">请使用微信扫一扫登录 <span class="opt" @click="refreshCode">刷新</span></div>
                <div class="qr-code-img mb-24">
                    <a-spin :spinning="!qrcodesrc">
                        <img :src="qrcodesrc" alt="">
                    </a-spin>
                </div>
            </div>
        </a-form>
    </a-modal>
</template>

<script setup>
import { defineProps, defineEmits, computed, ref, onBeforeUnmount } from 'vue';
import { bindQrcode, checkBindQrcode } from 'api/modules/api.account'
import { XsyMessage } from '@/libs/util.toast'
import userInfoStore from '@/stores/userInfo.js'

const props = defineProps({
    modelValue: {
        type: Boolean,
    },
});

const emit = defineEmits(['update:modelValue', 'refreshInfo']);
const modalVisible = computed({
    get: () => props.modelValue,
    set: v => emit('update:modelValue', v),
});


// 获取二维码
const uuid = ref('')
const qrcodesrc = ref('')
const getQrcode = function () {
    bindQrcode().then(res => {
        uuid.value = res.data.uuid
        qrcodesrc.value = res.data.qrCode
        checkQrCode()
    })
}

getQrcode()

// 检查二维码
let refresTimer = null
const checkQrCode = function () {
    if (refresTimer) {
        clearInterval(refresTimer)
    }

    refresTimer = setInterval(function () {
        checkBindQrcode({ uuid: uuid.value }).then(res => {
            if (res.data.status == '1' || res.code != '0') {
                clearInterval(refresTimer)
                refresTimer = null
                XsyMessage.warning('操作成功');
                emit('update:modelValue', false)
                userInfoStore().getUserInfo().then(() => { })
            }
        }).catch((err) => {
            clearInterval(refresTimer)
            refresTimer = null
        })
    }, 2000)
}

// 刷新二维码
const refreshCode = function () {
    clearInterval(refresTimer)
    refresTimer = null
    getQrcode()
}


onBeforeUnmount(() => {
    clearInterval(refresTimer)
})

const handleOk = () => {
    emit('update:modelValue', false)
}

</script>

<style lang="scss" scoped>
.qr-code-img {
    display: flex;
    align-items: center;
    justify-content: center;

    img {
        width: 190px;
        height: 190px;
    }
}

.opt {
    color: #07F;
}
</style>
